import os
import requests
import re
from bs4 import BeautifulSoup
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from aliyunsdkalidns.request.v20150109 import DescribeDomainRecordsRequest, AddDomainRecordRequest, UpdateDomainRecordRequest


def get_ip_address():
    url = 'https://2025.ip138.com/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive'
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            page_text = soup.get_text()
            ipv4_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
            match = re.search(ipv4_pattern, page_text)
            if match:
                return match.group(0)
            else:
                return None
        else:
            return None
    except requests.RequestException:
        return None


def manage_domain_record(access_key_id, access_key_secret, region_id, domain_name, rr, record_type, ip_address):
    client = AcsClient(access_key_id, access_key_secret, region_id)

    # 先查询域名已有的解析记录
    request = DescribeDomainRecordsRequest.DescribeDomainRecordsRequest()
    request.set_DomainName(domain_name)
    response = client.do_action_with_exception(request)
    import json
    records = json.loads(response)

    record_exists = False
    record_id = None
    for record in records.get('DomainRecords', {}).get('Record', []):
        if record.get('RR') == rr and record.get('Type') == record_type:
            record_exists = True
            record_id = record.get('RecordId')
            break

    if record_exists:
        # 更新记录
        request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
        request.set_RecordId(record_id)
        request.set_RR(rr)
        request.set_Type(record_type)
        request.set_Value(ip_address)
        result = client.do_action_with_exception(request)
        print(f"更新域名解析记录结果: {result}")
    else:
        # 添加记录
        request = AddDomainRecordRequest.AddDomainRecordRequest()
        request.set_DomainName(domain_name)
        request.set_RR(rr)
        request.set_Type(record_type)
        request.set_Value(ip_address)
        result = client.do_action_with_exception(request)
        print(f"添加域名解析记录结果: {result}")


if __name__ == "__main__":
    access_key_id = os.getenv('ACCESS_KEY_ID')
    access_key_secret = os.getenv('ACCESS_KEY_SECRET')
    region_id = os.getenv('REGION_ID')
    domain_name = os.getenv('DOMAIN_NAME')
    rr = os.getenv('RR')
    record_type = os.getenv('RECORD_TYPE')

    ip_address = get_ip_address()
    if ip_address:
        manage_domain_record(access_key_id, access_key_secret, region_id, domain_name, rr, record_type, ip_address)
    else:
        print("未成功获取到IP地址，无法进行域名解析操作。")